<?php
require_once("../Spac/model/Auth.Class.php");
class Customer extends Controller {

	var $MethodAccessControlType	= 'allow';
	var $AccessMethods		= array(
										'execute','getList',
										'viewWrite','executeWrite',
										'viewDetail','viewDetailConfirm',
										'viewModifyConfirm','viewModify','executeModify',
										'viewDeleteConfirm','executeDelete',
										'executeWriteComments',"executeDeleteComments"
								);

	var $category;
	var $view_dir			= "/customer";

	var $Auth;				//인증 obj
	var $Dao = null;	

	var $categorys = array("notice","qna","free");
	
	function Customer($Dao = null) {

		//컨트롤러 초기화
		$this->initController();
		
		//----------------------- 다른 클래스에서 불러 사용할것을 대비하여 Dao object를 전달받은경우 그대로 사용할 수 있도록 설계
		$this->Dao = $Dao;
		if($this->Dao == null) {
			$this->getControllerInstance("Dao");
			$this->Dao->Connect();
		}

		$this->getControllerInstance("Paging");		//페이징
		$this->Auth		= new Auth($this->Dao);		//인증

		$this->setLayout("sub");	//기본레이아웃 셋
		$this->layout['left']		= $this->view_dir."/left.html";		//서브메뉴 뷰 재정의

	}

	function execute() {
		$this->getList();
	}

	function getList() {

		$this->category		= $this->args[0];
		$this->page			= $this->args[1];

		if(!$this->category) {
			$this->category = 'notice';
		}

		$this->checkCategory();

		//페이징변수세팅
		if(!$this->page)	$this->page		= 1;
		if(!$this->pgSize)	$this->pgSize	= 10;
		if(!$this->blcSize) $this->blcSize	= 5;

		$this->first		= $this->pgSize*($this->page-1);
		$this->page_url		= "/Customer/getList/".$this->category;

		$query = "Select SQL_CALC_FOUND_ROWS * From customer Where del_code = 0 And category = ? Order By bbs_no DESC Limit $this->first, $this->pgSize";
		$param = $this->category;
		$this->Dao->executeBindingQuery($query,$param);
		$Result = $this->Dao->result;

		//총레코드수 구하기
		$query = "Select FOUND_ROWS()";
		$this->Dao->executeQuery($query);
		$this->total_record = $this->Dao->getResult();	

		$article_no			= $this->total_record - ($this->page-1)*$this->pgSize;

		$this->bbs_list = array();
		while($rows = mysql_fetch_object($Result)) {

			$rows->article_no		= $article_no;			
			$rows->reg_date_view	= substr($rows->reg_date,0,10);
			$rows->subjects			= htmlspecialchars(stripslashes($rows->subjects));
			$rows->contents			= nl2br(htmlspecialchars(stripslashes($rows->contents)));
			$this->bbs_list[] = $rows;

			$article_no--;
		}

		$this->Paging->initPaging($this->total_record, $this->blcSize, $this->pgSize, $this->page, $this->page_url);
		$this->Paging->getPaging();

		$this->result_uri = $this->view_dir."/list.html";
		$this->dispatcher();

		
	}

	function viewWrite() {

		$this->category		= $this->args[0];

		$this->checkCategory();

		if($this->category == 'notice') $this->Auth->checkAdmin();

		$this->result_uri = $this->view_dir."/write.html";
		$this->dispatcher();
		
	}

	function executeWrite() {

		$this->category				= $_POST['category'];
		$this->user_name			= $_POST['user_name'];
		$this->user_email			= $_POST['user_email'];
		$this->user_phone			= $_POST['user_phone1'] ."-".$_POST['user_phone2']."-".$_POST['user_phone3'];
		$this->user_mobile			= $_POST['user_mobile1'] ."-".$_POST['user_mobile2']."-".$_POST['user_mobile3'];
		$this->subjects				= $_POST['subjects'];
		$this->contents				= $_POST['contents'];
		$this->user_passwd			= $_POST['user_passwd'];
		$this->secret				= $_POST['secret'];
		if(!$this->secret) $this->secret = 0;

		$this->user_id				= $this->Auth->admin_id;
		$this->user_ip				= $_SERVER['REMOTE_ADDR'];
		$this->user_browser			= $_SERVER["HTTP_USER_AGENT"];

		$this->checkCategory();

		if($this->category == 'notice') $this->Auth->checkAdmin();

		$query = "

			Insert Into
				customer 
				(
					category,
					user_id,
					user_passwd,
					user_name,
					user_email,
					user_phone,
					user_mobile,
					subjects,
					contents,
					user_ip,
					user_browser,
					secret					
				)

			Values
				(
					?,
					?,
					password(?),
					?,
					?,
					?,
					?,
					?,
					?,
					?,
					?,
					?
				)

		";
		$param = array(

					$this->category,
					$this->user_id,
					$this->user_passwd,
					$this->user_name,
					$this->user_email,
					$this->user_phone,
					$this->user_mobile,
					$this->subjects,
					$this->contents,
					$this->user_ip,
					$this->user_browser,
					$this->secret		

		);

		$this->Dao->executeBindingQuery($query,$param);

		$this->result_uri = "/Customer/getList/".$this->category;
		$this->redirect();

	}






	function viewDetail() {

		$this->category		= $this->args[0];
		$this->bbs_no		= $this->args[1];
		$this->page			= $this->args[2];

		$this->checkCategory();

		$this->detail_info	= $this->getBbsDetailInfo($this->bbs_no);
		$this->detail_info->contents_view		= nl2br(htmlspecialchars(stripslashes($this->detail_info->contents)));

		//비밀글 체크
		if(!$this->Auth->isAdmin) {

			if($this->detail_info->secret) {
					
				//--- post로 비밀번호가 넘어왔는지 확인한다.
				$this->user_passwd			= $_POST['user_passwd'];

				//비밀번호가 안넘어왔으면 비밀번호 입력 폼화면으로 이동
				if(!$this->user_passwd) {

					$this->result_uri = "/Customer/viewDetailConfirm/".$this->category."/".$this->bbs_no."/".$this->page;
					$this->redirect();
					exit;

				//비밀번호가 넘어왔으면 체크
				} else {

					$this->checkPassword($this->bbs_no,$this->user_passwd);

				}

			}

		}

		//댓글 가져오기
		if($this->detail_info->comments) {
			$this->comments_list = $this->getBbsCommentsList($this->bbs_no);
		}


//		print_r($this->comments_list);

		$this->result_uri = $this->view_dir."/view.html";
		$this->dispatcher();

	
	}

	function getBbsDetailInfo($bbs_no) {
		$query = " Select * From customer where bbs_no = ? and del_code = 0 ";
		$param = $bbs_no;
		$this->Dao->executeBindingQuery($query,$param);

		if(!$this->Dao->getNumRows()) {
			$this->ErrorBackMsg("죄송합니다. 삭제되었거나 없는 글입니다.");	
			exit;
		}

		return $this->Dao->getFetchObject();
	}



	//--------------- comments

	function getBbsCommentsList($bbs_no) {

		$query = " Select * From customer_comments Where del_code = 0 and ref_bbs_no = ? Order By comm_no";
		$param = $bbs_no;
		$this->Dao->executeBindingQuery($query,$param);
		$Result = $this->Dao->result;

		$this->comments_list = array();
		while($Rows = mysql_fetch_object($Result)) {

			$Rows->contents_view		= nl2br(htmlspecialchars(stripslashes($Rows->contents)));
			$this->comments_list[]	= $Rows;

		}

		return $this->comments_list;
	
	}










	function executeWriteComments() {

		$this->bbs_no		= $_POST['bbs_no'];
		$this->category		= $_POST['category'];
		$this->page			= $_POST['page'];

		$this->user_name	= $_POST['user_name'];
		$this->user_passwd	= $_POST['user_passwd'];
		$this->contents		= $_POST['contents'];

		$this->user_id				= $this->Auth->admin_id;
		$this->user_ip				= $_SERVER['REMOTE_ADDR'];
		$this->user_browser			= $_SERVER["HTTP_USER_AGENT"];

		$this->checkCategory();

		$query = "
			Insert Into
				customer_comments
				(
					ref_bbs_no,
					user_id,
					user_passwd,
					user_name,
					contents,
					user_ip,
					user_browser
				)
			
			Values
				(
					?,
					?,
					password(?),
					?,
					?,
					?,
					?
				)
		";
		$param = array(
						$this->bbs_no,
						$this->user_id,
						$this->user_passwd,
						$this->user_name,
						$this->contents,
						$this->user_ip,
						$this->user_browser
				);

		$this->Dao->executeBindingQuery($query,$param);

		//댓글수 싱크맞추기
		$this->syncCommentsNum($this->bbs_no);

		//글보기 페이지로 이동
		$this->result_uri = "/Customer/viewDetail/".$this->category."/".$this->bbs_no."/".$this->page;
		$this->redirect();
		
	}

	function syncCommentsNum($bbs_no) {

		//실제코멘트 수 계산
		$query = " Select count(*) From customer_comments Where del_code = 0 and ref_bbs_no = ? ";
		$param = $bbs_no;
		$this->Dao->executeBindingQuery($query,$param);
		$comment_num = $this->Dao->getResult();

		//싱크맞추기
		$query = "Update customer Set comments = ? Where bbs_no = ?";
		$param = array($comment_num,$bbs_no);
		$this->Dao->executeBindingQuery($query,$param);
	
	}








	

	

	function viewDetailConfirm() {

		$this->category		= $this->args[0];
		$this->bbs_no		= $this->args[1];
		$this->page			= $this->args[2];

		$this->checkCategory();

		$this->result_uri = $this->view_dir."/view_confirm.html";
		$this->dispatcher();

		
	}








	function viewModifyConfirm() {

		$this->category		= $this->args[0];
		$this->bbs_no		= $this->args[1];
		$this->page			= $this->args[2];

		$this->checkCategory();

		if($this->Auth->isAdmin) {
			$this->result_uri = "/Customer/viewModify/".$this->category."/".$this->bbs_no."/".$this->page;
			$this->redirect();
			exit;
		}

		$this->result_uri = $this->view_dir."/modify_confirm.html";
		$this->dispatcher();

		
	}


	function viewModify() {

		$this->category		= $this->args[0];
		$this->bbs_no		= $this->args[1];
		$this->page			= $this->args[2];

		$this->checkCategory();

		$this->user_passwd	= $_POST['user_passwd'];

		if(!$this->Auth->isAdmin) {
			$this->checkPassword($this->bbs_no,$this->user_passwd);
		}

		$this->detail_info						= $this->getBbsDetailInfo($this->bbs_no);
		$this->detail_info->user_phone_array	= explode("-",$this->detail_info->user_phone);
		$this->detail_info->user_mobile_array	= explode("-",$this->detail_info->user_mobile);
		
		$this->result_uri = $this->view_dir."/modify.html";
		$this->dispatcher();

	}

	function executeModify() {

		
		$this->category				= $_POST['category'];
		$this->bbs_no				= $_POST['bbs_no'];
		$this->page					= $_POST['page'];

		$this->user_name			= $_POST['user_name'];
		$this->user_email			= $_POST['user_email'];
		$this->user_phone			= $_POST['user_phone1'] ."-".$_POST['user_phone2']."-".$_POST['user_phone3'];
		$this->user_mobile			= $_POST['user_mobile1'] ."-".$_POST['user_mobile2']."-".$_POST['user_mobile3'];
		$this->subjects				= $_POST['subjects'];
		$this->contents				= $_POST['contents'];
		$this->user_passwd			= $_POST['user_passwd'];
		$this->secret				= $_POST['secret'];
		if(!$this->secret) $this->secret = 0;

		$this->checkCategory();
		
		if(!$this->Auth->isAdmin) {
			$this->checkPassword($this->bbs_no,$this->user_passwd);
		}

		$query = "
			Update 
				customer 
			Set
				user_name		= ?,
				user_email		= ?,
				user_phone		= ?,
				user_mobile		= ?,
				subjects		= ?,
				contents		= ?,
				secret			= ?
			Where
				bbs_no			= ?
		";
		$param = array(
				$this->user_name,
				$this->user_email,
				$this->user_phone,
				$this->user_mobile,
				$this->subjects,
				$this->contents,
				$this->secret,
				$this->bbs_no
		);
		$this->Dao->executeBindingQuery($query,$param);

		$this->result_uri = "/Customer/viewDetail/".$this->category."/".$this->bbs_no."/".$this->page;
		$this->redirect();
		
	}


	function checkPassword($bbs_no,$user_passwd) {
		
		$query = " Select count(*) From customer where del_code = 0 and bbs_no = ? and user_passwd = password(?) ";
		$param = array($bbs_no,$user_passwd);
		$this->Dao->executeBindingQuery($query,$param);

		if(!$this->Dao->getResult()) {
			$this->ErrorBackMsg("비밀번호가 일치하지 않습니다. 다시한번 입력해주세요");	
			exit;
		}

	}



	function viewDeleteConfirm() {

		$this->category		= $this->args[0];
		$this->bbs_no		= $this->args[1];
		$this->page			= $this->args[2];

		$this->checkCategory();

		if($this->Auth->isAdmin) {
			$this->result_uri = "/Customer/executeDelete/".$this->category."/".$this->bbs_no."/".$this->page;
			$this->redirect();
			exit;
		}

		$this->bbs_data		= $this->getBbsDetailInfo($this->bbs_no);
		if($this->bbs_data->comments > 0) {
			$this->ErrorBackMsg("답글이 있는 글은 삭제하실 수 없습니다.");	
			exit;
		}

		$this->result_uri = $this->view_dir."/delete_confirm.html";
		$this->dispatcher();		
		
	}


	function executeDelete() {

		$this->category		= $this->args[0];
		$this->bbs_no		= $this->args[1];
		$this->page			= $this->args[2];
		$this->user_passwd	= $_POST['user_passwd'];

		$this->checkCategory();
	
		if(!$this->Auth->isAdmin) {
			$this->checkPassword($this->bbs_no,$this->user_passwd);
		}

		$query = " Update customer Set del_code = 1, mod_date = NOW() Where bbs_no = ? ";
		$param = array($this->bbs_no);
		$this->Dao->executeBindingQuery($query,$param);

		//리스트로 이동
		$this->result_uri = "/Customer/getList/".$this->category;
		$this->redirect();		
		
	}



	function executeDeleteComments() {

		$this->category		= $this->args[0];
		$this->bbs_no		= $this->args[1];
		$this->page			= $this->args[2];
		$this->comm_no		= $this->args[3];

		$this->checkCategory();

		//관리자체크
		$this->Auth->checkAdmin();
		
		//삭제
		$query = " Update customer_comments Set del_code = 1 Where del_code = 0 and comm_no = ? ";
		$param = $this->comm_no;
		$this->Dao->executeBindingQuery($query,$param);

		//코멘트수 싱크
		$this->syncCommentsNum($this->bbs_no);

		//글조회로 이동
		$this->result_uri = "/Customer/viewDetail/".$this->category."/".$this->bbs_no."/".$this->page;
		$this->redirect();
		
	}

	function getRecentData($category,$num) {

		$query = "Select bbs_no,category,subjects,reg_date From customer Where del_code = 0 And category = ? Order By reg_date DESC Limit 0,?";
		$param = array($category,$num);
		$this->Dao->executeBindingQuery($query,$param);
		$Result = $this->Dao->result;

		$this->recent_bbs_list = array();
		while($rows = mysql_fetch_object($Result)) {

			$rows->subjects				= htmlspecialchars(stripslashes($rows->subjects));
			$rows->subjects				= $this->resizeString($rows->subjects,20);
			$rows->reg_date_view		= str_replace("-","/",substr($rows->reg_date,5,5));

			$this->recent_bbs_list[]	= $rows;

		}

		return $this->recent_bbs_list;
		
	}


	
	
	
	
	

	

	function checkCategory() {
		
		if(!in_array($this->category,$this->categorys)) {
			$this->ErrorBackMsg("잘못된 호출입니다.");
			exit;
		}

	}
	
	
	
	//---- cut string -----
	function resizeString($Str, $size, $addStr="...")  { 
	    if(mb_strlen($Str, "UTF-8") > $size) return mb_substr($Str, 0, $size, "UTF-8").$addStr; 
	    else return $Str; 
	} 







	
}
?>